package com.pt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pt.entity.ForumSection;
import com.pt.entity.ForumTopic;
import com.pt.entity.ForumReply;
import com.pt.entity.ForumReplyLike;
import com.pt.entity.ForumTopicLike;
import com.pt.entity.User;
import com.pt.mapper.ForumSectionMapper;
import com.pt.mapper.ForumTopicMapper;
import com.pt.mapper.ForumReplyMapper;
import com.pt.mapper.ForumReplyLikeMapper;
import com.pt.mapper.ForumTopicLikeMapper;
import com.pt.service.ForumService;
import com.pt.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class ForumServiceImpl implements ForumService {
    
    private final ForumSectionMapper forumSectionMapper;
    private final ForumTopicMapper forumTopicMapper;
    private final ForumReplyMapper forumReplyMapper;
    private final ForumReplyLikeMapper forumReplyLikeMapper;
    private final ForumTopicLikeMapper forumTopicLikeMapper;
    private final UserService userService;
    
    @Override
    public List<ForumSection> getAllSections() {
        List<ForumSection> sections = forumSectionMapper.selectList(
            new QueryWrapper<ForumSection>().orderByAsc("sort_order")
        );
        
        // 为每个板块添加帖子数量统计
        for (ForumSection section : sections) {
            Long topicCountLong = forumTopicMapper.selectCount(
                new QueryWrapper<ForumTopic>()
                    .eq("section_id", section.getId())
                    .eq("is_deleted", false)
            );
            section.setTopicCount(topicCountLong.intValue());
        }
        
        return sections;
    }
    
    @Override
    public IPage<ForumTopic> getTopicsBySection(Integer sectionId, Page<ForumTopic> page) {
        QueryWrapper<ForumTopic> wrapper = new QueryWrapper<>();
        wrapper.eq("section_id", sectionId)
               .eq("is_deleted", false)
               .orderByDesc("is_sticky")
               .orderByDesc("last_reply_time");
        return forumTopicMapper.selectPage(page, wrapper);
    }
    
    @Override
    public ForumTopic getTopicById(Long topicId) {
        return forumTopicMapper.selectOne(
            new QueryWrapper<ForumTopic>()
                .eq("id", topicId)
                .eq("is_deleted", false)
        );
    }
    
    @Override
    public IPage<ForumReply> getRepliesByTopic(Long topicId, Page<ForumReply> page) {
        QueryWrapper<ForumReply> wrapper = new QueryWrapper<>();
        wrapper.eq("topic_id", topicId)
               .eq("is_deleted", false)
               .orderByAsc("created_time");
        return forumReplyMapper.selectPage(page, wrapper);
    }
    
    @Override
    public ForumReply getReplyById(Long replyId) {
        return forumReplyMapper.selectById(replyId);
    }
    
    @Override
    @Transactional
    public ForumTopic createTopic(ForumTopic topic) {
        forumTopicMapper.insert(topic);
        return topic;
    }
    
    @Override
    @Transactional
    public ForumReply createReply(ForumReply reply) {
        // 设置楼层号
        Long count = forumReplyMapper.selectCount(
            new QueryWrapper<ForumReply>()
                .eq("topic_id", reply.getTopicId())
                .eq("is_deleted", false)
        );
        Integer floor = count.intValue() + 1;
        reply.setFloor(floor);
        
        forumReplyMapper.insert(reply);
        
        // 更新主题的回复信息
        ForumTopic topic = forumTopicMapper.selectById(reply.getTopicId());
        if (topic != null) {
            topic.setReplyCount(topic.getReplyCount() + 1);
            topic.setLastReplyId(reply.getId());
            topic.setLastReplyTime(LocalDateTime.now());
            forumTopicMapper.updateById(topic);
        }
        
        return reply;
    }
    
    @Override
    @Transactional
    public void deleteTopic(Long topicId) {
        ForumTopic topic = forumTopicMapper.selectById(topicId);
        if (topic != null) {
            topic.setIsDeleted(true);
            forumTopicMapper.updateById(topic);
        }
    }
    
    @Override
    @Transactional
    public void deleteReply(Long replyId) {
        ForumReply reply = forumReplyMapper.selectById(replyId);
        if (reply != null) {
            reply.setIsDeleted(true);
            forumReplyMapper.updateById(reply);
            
            // 更新主题回复数
            ForumTopic topic = forumTopicMapper.selectById(reply.getTopicId());
            if (topic != null && topic.getReplyCount() > 0) {
                topic.setReplyCount(topic.getReplyCount() - 1);
                forumTopicMapper.updateById(topic);
            }
        }
    }
    
    @Override
    @Transactional
    public void increaseViewCount(Long topicId) {
        ForumTopic topic = forumTopicMapper.selectById(topicId);
        if (topic != null) {
            topic.setViewCount(topic.getViewCount() + 1);
            forumTopicMapper.updateById(topic);
        }
    }
    
    @Override
    @Transactional
    public void toggleSticky(Long topicId) {
        ForumTopic topic = forumTopicMapper.selectById(topicId);
        if (topic != null) {
            topic.setIsSticky(!topic.getIsSticky());
            forumTopicMapper.updateById(topic);
        }
    }
    
    @Override
    @Transactional
    public void toggleLock(Long topicId) {
        ForumTopic topic = forumTopicMapper.selectById(topicId);
        if (topic != null) {
            topic.setIsLocked(!topic.getIsLocked());
            forumTopicMapper.updateById(topic);
        }
    }
    
    @Override
    public boolean isTopicAuthor(Long topicId, String username) {
        User user = userService.getUserByUsername(username);
        if (user == null) return false;
        
        ForumTopic topic = forumTopicMapper.selectById(topicId);
        return topic != null && topic.getAuthorId().equals(user.getId());
    }
    
    @Override
    public boolean isReplyAuthor(Long replyId, String username) {
        User user = userService.getUserByUsername(username);
        if (user == null) return false;
        
        ForumReply reply = forumReplyMapper.selectById(replyId);
        return reply != null && reply.getAuthorId().equals(user.getId());
    }
    
    @Override
    @Transactional
    public void likeReply(Long replyId, Long userId) {
        // 检查是否已经点赞
        boolean exists = forumReplyLikeMapper.selectCount(
                new QueryWrapper<ForumReplyLike>()
                        .eq("reply_id", replyId)
                        .eq("user_id", userId)
        ) > 0;

        if (exists) {
            // 取消点赞
            forumReplyLikeMapper.delete(
                    new QueryWrapper<ForumReplyLike>()
                            .eq("reply_id", replyId)
                            .eq("user_id", userId)
            );
            // 更新回复点赞数
            forumReplyMapper.decrementLikeCount(replyId);
        } else {
            // 添加点赞记录
            ForumReplyLike replyLike = new ForumReplyLike();
            replyLike.setReplyId(replyId);
            replyLike.setUserId(userId);
            replyLike.setCreatedTime(LocalDateTime.now());
            forumReplyLikeMapper.insert(replyLike);

            // 更新回复点赞数
            forumReplyMapper.incrementLikeCount(replyId);
        }
    }
    
    @Override
    @Transactional
    public void likeTopic(Long topicId, Long userId) {
        // 检查是否已经点赞
        boolean exists = forumTopicLikeMapper.selectCount(
                new QueryWrapper<ForumTopicLike>()
                        .eq("topic_id", topicId)
                        .eq("user_id", userId)
        ) > 0;

        if (exists) {
            // 取消点赞
            forumTopicLikeMapper.delete(
                    new QueryWrapper<ForumTopicLike>()
                            .eq("topic_id", topicId)
                            .eq("user_id", userId)
            );
            // 更新主题点赞数
            forumTopicMapper.decrementLikeCount(topicId);
        } else {
            // 添加点赞记录
            ForumTopicLike topicLike = new ForumTopicLike();
            topicLike.setTopicId(topicId);
            topicLike.setUserId(userId);
            topicLike.setCreatedTime(LocalDateTime.now());
            forumTopicLikeMapper.insert(topicLike);

            // 更新主题点赞数
            forumTopicMapper.incrementLikeCount(topicId);
        }
    }
} 